from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from . import models


# 自定制登录认证功能
class UsernameMobileAuthBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        try:
            user = models.User.objects.get(Q(username=username) | Q(mobile=username))
        except models.User.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user
